package com.zzsin.gtestreporter.filter;

import com.zzsin.gtestreporter.Constants;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

@WebFilter(filterName = "MyFilter",urlPatterns = "/coverage_html_report/*")
public class FirstFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    String readFileStr(String fileName) {
        byte[] bytes = new byte[0];
        try {
            bytes = Files.readAllBytes(Paths.get(fileName));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        String content = new String(bytes, StandardCharsets.UTF_8);
        return content;
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String path = request.getRequestURI();

        if(path.startsWith("/coverage_html_report/")){
            System.out.println(path);

            String reportDir = "/EYE/" + File.separator + path;

            File f = new File(reportDir);
            if(f.exists()){
                String html = readFileStr(reportDir);
                response.getWriter().println(html);
            }
            else {
                response.getWriter().println("not exists");
            }
        }
        else {
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }

    @Override
    public void destroy() {

    }
}
